﻿
using Hotel.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hotel.DAL
{
    public class ShopDAL
    {
        public ShopDAL(HotelContext hotelContext)
        {
            HotelContext = hotelContext;
        }

        public HotelContext HotelContext { get; }

        //添加
        public int ShopAdd(ShopModel shop)
        {
            shop.IsDel = false;
            HotelContext.ShopInfo.Add(shop);
            return HotelContext.SaveChanges();
        }

        //查询 name
        public int GetShopName(string name)
        {
            return HotelContext.ShopInfo.Where(x => x.Name == name).Count();
        }

        /// <summary>
        /// 显示list
        /// </summary>
        /// <param name="toCount"></param>
        /// <param name="toPage"></param>
        /// <param name="name"></param>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <returns></returns>

        public List<ShopModel> GetShopList(out int toCount, out int toPage, string? name, int index = 1, int size = 3)
        {
            //查询显示所有的数据
            var list = HotelContext.ShopInfo.Where(x => x.IsDel == false).ToList();
            //根据门店名称模糊查询
            if (!string.IsNullOrEmpty(name))
            {
                list = list.Where(x => x.Name.Contains(name)).ToList();
            }
            //分页
            //计算总条数
            toCount = list.Count();
            toPage =  (int)Math.Ceiling(toCount * 1.0 / size);

            list = list.OrderByDescending(x => x.Id).Skip((index-1)*size).Take(size).ToList();
            return list;
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"多个ids字符串></param>
        /// <returns></returns>
        public int DelShopId(string ids)
        {
            //1.字符串转为数组
            var idsArr = ids.Split(',');
            //2.循环数组进行单个删除
            foreach(var id in idsArr){
                //3.根据id获取门店的某一项 
                //Find 查找
                //var info = HotelContext.ShopInfo.Find(Convert.ToInt32(idsArr));
                var info = HotelContext.ShopInfo.Where(x => x.Id == Convert.ToInt32(id)).FirstOrDefault();
                info.IsDel = true;
            }
            return HotelContext.SaveChanges();
        }

        /// <summary>
        /// 批量修改状态
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="steta"></param>
        /// <returns></returns>
        public int Upsteta(string ids,int steta)
        {
            //1.将ids变成数组
            var idsArr = ids.Split(',');
            foreach (var id in idsArr)
            {
                //2.通过id找到这项
                var info = HotelContext.ShopInfo.Find(Convert.ToInt32(id));
                info.State = steta;
            }
            //3.更新数据库
            return HotelContext.SaveChanges();
        }

    }
}
